<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------

namespace api\home\controller;

use app\admin\model\MemberModel;
use cmf\controller\RestBaseController;
use think\Request;
use app\admin\model\UserModel;

//专家
class ExpertController extends RestBaseController
{
    /**
     * @param Request $request
     * @throws \think\exception\DbException
     * 聊神专家列表
     */
    public function index(Request $request)
    {
        if (!$request->isPost()) {
            $this->error('请求方式错误');
        }
        $this->checkValidate($request->param(), config('check.type'));
        $member = MemberModel::get($this->getUserId());
        $users = UserModel::field('id,avatar,user_nickname,tag,signature')
            ->where(function ($query) use ($request, $member) {
                if ($request->type == 3) {//我关注的专家
                    $ids = $member->users->column('id');
                    $query->whereIn('id', $ids);
                } else {
                    $query->whereLike('type', "%$request->type%");
                }
            })
            ->order('sort desc')
            ->paginate(9)->each(function ($item, $value) use ($member, $request) {
                $item->is_attention = $member->users()->where('user_id', $item->id)->find() ? true : false;
            });
        $this->success('成功', $users);
    }

    /**
     * @param Request $request
     * 关注专家
     */
    public function attention(Request $request)
    {
        if (!$request->isPost()) {
            $this->error('请求方式错误');
        }
        $this->checkValidate($request->param(), config('check.id'));
        $member = MemberModel::get($this->getUserId());
        if (!$member->users()->where('user_id', $request->id)->find()) {
            $member->users()->save($request->id, ['create_time' => time()]);
        }
        //更改用户关注数量
        $member->save(['follow_num' => count($member->users)]);
        $this->success('成功');
    }

    /**
     * @param Request $request
     * 取消关注
     */
    public function unfollow(Request $request)
    {
        if (!$request->isDelete()) {
            $this->error('请求方式错误');
        }
        $this->checkValidate($request->param(), config('check.id'));
        $member = MemberModel::get($this->getUserId());
        $member->users()->detach($request->id);
        //更改用户关注数量
        $member->save(['follow_num' => count($member->users)]);
        $this->success('成功');
    }
}
